package com.xgpro.common.utils;

import com.alibaba.fastjson.JSON;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.websocket.CustomHandler;
import com.xgpro.common.websocket.dto.PushInformationDTO;
import com.xgpro.domain.messagemanage.entity.Message;
import com.xgpro.domain.talentintroduction.entity.User;
import com.xgpro.mobile.message.service.MessageService;
import com.xgpro.pc.rolemanage.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: xgpro__dev
 * @description: 消息工具类
 * @author: likai
 * @create: 2019-09-28 01:29
 **/
@Component
public class SendMsgUtil {


    @Resource
    private CustomHandler customHandler;

    @Resource
    private MessageService messageService;

    @Resource
    private UserService userService;

    /**
     * 发送消息工具类，传入对应参数即可
     *
     * @param title   消息标题
     * @param content 消息内容
     */
    public void sendMsg(String title, String content, Integer userId) {

        //封装消息数据
        Message message = encapsulatingData(title, content);
        ArrayList<Integer> list = new ArrayList<>();
        list.add(userId);
        this.saveMsg(null, message, list);
    }

    /**
     * 发送消息工具类，传入对应参数即可
     *
     * @param type    发送消息的类型
     * @param title   消息标题
     * @param content 消息内容
     * @param userIds 消息接收者的id
     */
    public void sendMsg(Integer type, String title, String content, List<Integer> userIds) {

        //封装消息数据
        Message message = encapsulatingData(title, content);
        this.saveMsg(type, message, userIds);
    }

    private Message encapsulatingData(String title, String content) {
        Message message = new Message();
        message.setTitle(title);
        message.setContent(content);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        Object id1 = session.getAttribute("id");

        if (!ObjectUtils.isEmpty(id1)) {
            Integer id = (int) id1;
            User user = userService.getUserInfoByUserId(id);
            message.setSendUser(user.getUsername());
        }else {
            message.setSendUser("系统消息");
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateTime = LocalDateTime.now().format(dateTimeFormatter);
        message.setMsgTime(dateTime);
        return message;
    }

    /**
     * 发送消息到指定用户
     *
     * @param message
     * @param userIds
     */
    private void saveMsg(Integer type, Message message, List<Integer> userIds) {
        if (!CollectionUtils.isEmpty(userIds)) {
            int cnt1 = messageService.insert(message);
            if (cnt1 == 0) {
                throw new BusinessRuntimeException(ResultCodeEnum.MESSAGE_SEND_FAIL.getCode(), ResultCodeEnum.MESSAGE_SEND_FAIL.getMessage());
            }
            for (Integer userId : userIds) {

                //向数据库中插入用户、消息等数据
                int cnt3 = messageService.sendInform(userId, message.getId());
                if (cnt3 == 0) {
                    throw new BusinessRuntimeException(ResultCodeEnum.MESSAGE_SEND_FAIL.getCode(), ResultCodeEnum.MESSAGE_SEND_FAIL.getMessage());
                }

                String data = JSON.toJSONString(message);
                TextMessage textMessage = new TextMessage(data);
                customHandler.sendMessageToUser(userId + "", textMessage);
            }
        }

    }

    /**
     * 向所有连接用户推送数据
     *
     * @param type 消息的类型
     * @param obj  需要推送的消息
     */
    public void pushDataToAllUser(Integer type, Object obj) {

        PushInformationDTO informationDTO = new PushInformationDTO();
        informationDTO.setState(type);
        informationDTO.setData(obj);
        String data = JSON.toJSONString(informationDTO);
        TextMessage textMessage = new TextMessage(data);
        boolean flag = customHandler.sendMessageToAllUsers(textMessage);

    }
}
